package com.shxy.cloudclassroom.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.shxy.cloudclassroom.entity.dto.EditUserDTO;
import com.shxy.cloudclassroom.entity.pojo.*;
import com.shxy.cloudclassroom.service.*;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.shxy.cloudclassroom.utils.SystemConstant.*;

@Service
public class AdminServiceImpl implements AdminService {

    @Override
    // 获取管理员主页数据
    public com.shxy.cloudclassroom.entity.vo.AdminDashboardVO getAdminIndexData(HttpSession session, UserService userService,
                                               LearningResourceService learningResourceService,
                                               AssignmentService assignmentService,
                                               ForumPostService forumPostService,
                                               ForumReplyService forumReplyService,
                                               MajorService majorService) {
        User user = (User) session.getAttribute(LOGIN_USER);
        if (user == null) {
            return null;
        }
        //用户总数
        List<User> users = getAllUsers(user.getId(), userService);
        //管理员数量
        List<User> admins = getAllAdmins(userService);
        //资源数量
        List<LearningResource> resources = getAllResources(learningResourceService);
        //作业与考试资源数量
        List<Assignment> assignments = getAllAssignments(assignmentService);
        //获取帖子数量
        List<ForumPost> posts = getAllPosts(forumPostService);
        //回复列表
        List<ForumReply> replies = getAllReplies(forumReplyService);
        //创建用户映射，通过ID获取用户
        Map<Long, String> userMap = getUserMap(users);
        //创建专业映射
        Map<Integer, String> majorMap = getMajorMap(majorService);
        //创建帖子映射
        Map<Long, String> postMap = getPostMap(posts);
        
        // 封装到VO对象
        com.shxy.cloudclassroom.entity.vo.AdminDashboardVO adminDashboardVO = new com.shxy.cloudclassroom.entity.vo.AdminDashboardVO();
        adminDashboardVO.setUsers(users);
        adminDashboardVO.setAdmins(admins);
        adminDashboardVO.setResources(resources);
        adminDashboardVO.setAssignments(assignments);
        adminDashboardVO.setForums(posts);
        adminDashboardVO.setReplies(replies);
        adminDashboardVO.setUserMap(userMap);
        adminDashboardVO.setMajorMap(majorMap);
        adminDashboardVO.setPostMap(postMap);
        
        return adminDashboardVO;
    }

    @Override
    // 更新管理员头像
    public Map<String, Object> updateAvatar(MultipartFile file, HttpSession session, OssService ossService, UserService userService) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = (User) session.getAttribute(LOGIN_USER);
            if (user == null) {
                result.put("success", false);
                result.put("error", "用户未登录");
                return result;
            }
            // 上传头像到OSS
            String avatarUrl = ossService.uploadAvatar(file);
            // 更新用户头像信息
            user.setAvatar(avatarUrl);
            boolean updated = userService.updateById(user);
            if (updated) {
                // 更新session中的用户信息
                session.setAttribute(LOGIN_USER, user);
                result.put("success", true);
                result.put("url", avatarUrl);
            } else {
                result.put("success", false);
                result.put("error", "更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("error", "上传失败: " + e.getMessage());
        }
        return result;
    }

    @Override
    // 获取所有用户列表
    public List<User> getAllUsers(Long id, UserService userService) {
        return userService.list(new LambdaQueryWrapper<User>().ne(User::getId, id).ne(User::getDeleted, 1));
    }

    @Override
    // 获取所有管理员列表
    public List<User> getAllAdmins(UserService userService) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getRole, ORDINARY_ADMIN)
                .or()
                .eq(User::getRole, SUPER_ADMIN);
        return userService.list(wrapper);
    }

    @Override
    // 获取所有学习资源
    public List<LearningResource> getAllResources(LearningResourceService learningResourceService) {
        return learningResourceService.list();
    }

    @Override
    // 获取所有作业
    public List<Assignment> getAllAssignments(AssignmentService assignmentService) {
        return assignmentService.list();
    }

    @Override
    // 获取所有帖子
    public List<ForumPost> getAllPosts(ForumPostService forumPostService) {
        return forumPostService.list();
    }

    @Override
    // 获取所有回复
    public List<ForumReply> getAllReplies(ForumReplyService forumReplyService) {
        return forumReplyService.list();
    }

    @Override
    // 获取用户映射
    public Map<Long, String> getUserMap(List<User> users) {
        return users.stream().collect(Collectors.toMap(User::getId, User::getUsername));
    }

    @Override
    // 获取专业映射
    public Map<Integer, String> getMajorMap(MajorService majorService) {
        return majorService.list().stream().collect(Collectors.toMap(Major::getId, Major::getName));
    }

    @Override
    // 获取帖子映射
    public Map<Long, String> getPostMap(List<ForumPost> posts) {
        return posts.stream().collect(Collectors.toMap(ForumPost::getId, ForumPost::getTitle));
    }

    @Override
    // 提升用户为管理员
    public Map<String, Object> promoteToAdmin(Long userId, UserService userService) {
        userService.updateAdminById(userId);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("error", "删除失败");
        return result;
    }

    @Override
    // 根据ID删除用户
    public Map<String, Object> delUserById(Long id, HttpSession session, UserService userService) {
        if (!verifyAdmin(session)) {
            throw new RuntimeException("权限不足~");
        }
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.set("deleted", '1').eq("id", id);
        boolean updated = userService.update(wrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("success", updated);
        result.put("error", updated ? null : "删除失败");
        return result;
    }

    @Override
    // 更新用户信息
    public Map<String, Object> updateUser(EditUserDTO editUserDTO, HttpSession session, UserService userService) {
        editUserDTO.setPassword(DigestUtils.md5DigestAsHex(editUserDTO.getPassword().getBytes(StandardCharsets.UTF_8)));
        User user = BeanUtil.copyProperties(editUserDTO, User.class);
        boolean updated = userService.update(user, new LambdaQueryWrapper<User>().eq(User::getId, user.getId()));
        Map<String, Object> result = new HashMap<>();
        result.put("success", updated);
        result.put("error", updated ? null : "删除失败");
        return result;
    }

    @Override
    // 将管理员降级为普通用户
    public Map<String, Object> demoteToUser(Long userId, HttpSession session, UserService userService) {
        //1.校验身份
        if (!verifyAdmin(session)) {
            throw new RuntimeException("权限不足");
        }
        //2.更新数据库数据
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.set("deleted", '1').eq("id", userId);
        boolean updated = userService.update(wrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("success", updated);
        result.put("error", updated ? null : "删除失败");
        return result;
    }

    @Override
    // 将普通用户提升为管理员
    public Map<String, Object> promoteUserToAdmin(Long userId, UserService userService) {
        // TODO: 实现将普通用户提升为管理员
        return null;
    }

    @Override
    // 根据ID删除管理员
    public Map<String, Object> delAdminById(Long id, HttpSession session, UserService userService) {
        if (!verifyAdmin(session)) {
            throw new RuntimeException("权限不足");
        }
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.set("deleted", '1').eq("id", id);
        userService.update(wrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "success");
        return result;
    }

    @Override
    // 删除学习资源
    public Map<String, Object> deleteResource(Long resourceId, DownloadHistoryService downloadHistoryService,
                                             ViewHistoryService viewHistoryService, AssignmentService assignmentService,
                                             AssignmentSubmissionService assignmentSubmissionService,
                                             LearningResourceService learningResourceService) {
        //1.删除关联的下载和浏览历史以及作为作业
        LambdaQueryWrapper<DownloadHistory> downloadHistoryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<ViewHistory> viewHistoryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Assignment> assignmentWrapper = new LambdaQueryWrapper<>();
        downloadHistoryWrapper.eq(DownloadHistory::getResourceId, resourceId);
        viewHistoryWrapper.eq(ViewHistory::getResourceId, resourceId);
        assignmentWrapper.eq(Assignment::getResourceId, resourceId);
        List<DownloadHistory> downloadHistories = downloadHistoryService.list(downloadHistoryWrapper);
        List<ViewHistory> viewHistories = viewHistoryService.list(viewHistoryWrapper);
        List<Assignment> assignments = assignmentService.list(assignmentWrapper);
        if (!downloadHistories.isEmpty()) {
            List<Long> ids = downloadHistories.stream().map(DownloadHistory::getId).toList();
            downloadHistoryService.removeBatchByIds(ids);
        }
        if (!viewHistories.isEmpty()) {
            List<Long> ids = viewHistories.stream().map(ViewHistory::getId).toList();
            viewHistoryService.removeBatchByIds(ids);
        }
        if (!assignments.isEmpty()) {
            List<Long> ids = assignments.stream().map(Assignment::getId).toList();
            for (Long assignmentId : ids) {
                deleteAssignment(assignmentId, assignmentSubmissionService, assignmentService);
            }
        }
        //2.删除资源
        boolean deleted = learningResourceService.removeById(resourceId);
        Map<String, Object> result = new HashMap<>();
        result.put("success", deleted);
        result.put("error", deleted ? null : "删除失败!");
        return result;
    }

    @Override
    // 获取学习资源详情
    public Map<String, Object> getResource(Long id, MajorService majorService, LearningResourceService learningResourceService) {
        LearningResource resource = learningResourceService.getById(id);
        Major major = majorService.getById(resource.getMajorId());
        Map<String, Object> result = new HashMap<>();
        result.put("id", resource.getId());
        result.put("title", resource.getTitle());
        result.put("major", major.getName());
        result.put("type", resource.getType());
        result.put("fileSize", resource.getFileSize());
        result.put("createTime", resource.getCreatedTime());
        result.put("status", resource.getStatus());
        result.put("downloadCount", resource.getDownloadCount());
        result.put("viewCount", resource.getViewCount());
        result.put("description", resource.getDescription());
        result.put("success", "success");
        return result;
    }

    @Override
    // 获取作业详情
    public Map<String, Object> getAssignment(Long id, MajorService majorService, AssignmentService assignmentService) {
        Assignment assignment = assignmentService.getById(id);
        Major major = majorService.getById(assignment.getMajorId());
        Map<String, Object> result = new HashMap<>();
        result.put("id", assignment.getId());
        result.put("title", assignment.getTitle());
        result.put("major", major.getName());
        result.put("createdTime", assignment.getCreatedTime());
        result.put("deadline", assignment.getDeadline());
        result.put("status", assignment.getStatus());
        result.put("description", assignment.getDescription());
        result.put("success", "success");
        return result;
    }

    @Override
    // 添加作业或考试
    public Map<String, Object> addAssignment(String title, Integer majorId, String description, String deadline,
                                             MultipartFile file, HttpSession session, OssService ossService,
                                             AssignmentService assignmentService) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = (User) session.getAttribute(LOGIN_USER);
            if (user == null) {
                result.put("success", false);
                result.put("error", "用户未登录");
                return result;
            }

            Assignment assignment = new Assignment();
            assignment.setTitle(title);
            assignment.setMajorId(majorId);
            assignment.setDescription(description);

            // 使用正确的格式解析日期时间
            DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; // ISO格式支持T字符
            LocalDateTime deadlineDateTime = LocalDateTime.parse(deadline, formatter);
            assignment.setDeadline(deadlineDateTime);

            assignment.setUploaderId(user.getId());
            assignment.setStatus(1); // 进行中
            assignment.setCreatedTime(LocalDateTime.now());
            assignment.setUpdatedTime(LocalDateTime.now());

            // 如果有上传文件
            if (file != null && !file.isEmpty()) {
                String fileUrl = ossService.uploadAvatar(file);
                assignment.setFileUrl(fileUrl);
            }

            boolean saved = assignmentService.save(assignment);
            result.put("success", saved);
            if (!saved) {
                result.put("error", "save失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("error", "发布失败: " + e.getMessage());
        }
        return result;
    }

    @Override
    // 删除作业或考试
    public Map<String, Object> deleteAssignment(Long assignmentId, AssignmentSubmissionService assignmentSubmissionService,
                                               AssignmentService assignmentService) {
        //1.删除关联的提交记录
        List<AssignmentSubmission> submissions = assignmentSubmissionService.list(new LambdaQueryWrapper<AssignmentSubmission>().eq(AssignmentSubmission::getAssignmentId, assignmentId));
        if (!submissions.isEmpty()) {
            List<Long> ids = submissions.stream().map(AssignmentSubmission::getId).toList();
            assignmentSubmissionService.removeBatchByIds(ids);
        }
        //2.删除作业或考试
        boolean deleted = assignmentService.removeById(assignmentId);
        Map<String, Object> result = new HashMap<>();
        result.put("success", deleted);
        result.put("error", deleted ? null : "删除失败!");
        return result;
    }

    @Override
    // 获取作业提交列表
    public Map<String, Object> getAssignmentSubmissions(Long assignmentId, AssignmentSubmissionService assignmentSubmissionService) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<AssignmentSubmission> submissions = assignmentSubmissionService
                    .list(new LambdaQueryWrapper<AssignmentSubmission>()
                            .eq(AssignmentSubmission::getAssignmentId, assignmentId));

            result.put("success", true);
            result.put("submissions", submissions);
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", "获取提交列表失败: " + e.getMessage());
        }
        return result;
    }

    @Override
    // 批改作业
    public Map<String, Object> gradeSubmission(Long submissionId, BigDecimal score, String comment,
                                               AssignmentSubmissionService assignmentSubmissionService) {
        Map<String, Object> result = new HashMap<>();
        try {
            AssignmentSubmission submission = new AssignmentSubmission();
            submission.setId(submissionId);
            submission.setScore(score);
            submission.setComment(comment);
            submission.setStatus(1); // 已批改

            boolean updated = assignmentSubmissionService.updateById(submission);

            if (updated) {
                result.put("success", true);
                // 获取更新后的submission数据
                AssignmentSubmission updatedSubmission = assignmentSubmissionService.getById(submissionId);
                result.put("submission", updatedSubmission);
            } else {
                result.put("success", false);
                result.put("error", "批改失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", "批改失败: " + e.getMessage());
        }
        return result;
    }

    @Override
    // 置顶帖子
    public Map<String, Object> topPost(Long postId, Integer isTop, ForumPostService forumPostService) {
        boolean updated = forumPostService.update(new UpdateWrapper<ForumPost>()
                .set("is_top", isTop)
                .eq("id", postId));
        Map<String, Object> result = new HashMap<>();
        result.put("success", updated);
        result.put("error", updated ? null : "操作失败!");
        return result;
    }

    @Override
    // 加精帖子
    public Map<String, Object> highlightPost(Long postId, Integer isElite, ForumPostService forumPostService) {
        boolean updated = forumPostService.update(new UpdateWrapper<ForumPost>()
                .set("is_elite", isElite)
                .eq("id", postId));
        Map<String, Object> result = new HashMap<>();
        result.put("success", updated);
        result.put("error", updated ? null : "操作失败!");
        return result;
    }

    @Override
    // 取消加精帖子
    public Map<String, Object> unhighlightPost(Long postId, ForumPostService forumPostService) {
        // TODO: 实现取消加精帖子
        return null;
    }

    @Override
    // 删除帖子
    public Map<String, Object> deletePost(Long postId, ForumReplyService forumReplyService, ForumPostService forumPostService) {
        //1.删除帖子关联的回复
        List<ForumReply> replies = forumReplyService.list(new LambdaQueryWrapper<ForumReply>().eq(ForumReply::getPostId, postId));
        if (!replies.isEmpty()) {
            List<Long> ids = replies.stream().map(ForumReply::getId).toList();
            forumReplyService.removeBatchByIds(ids);
        }
        //2.删除帖子
        boolean deleted = forumPostService.removeById(postId);
        Map<String, Object> result = new HashMap<>();
        result.put("success", deleted);
        result.put("error", deleted ? null : "删除失败!");
        return result;
    }

    @Override
    // 删除评论
    public Map<String, Object> deleteReply(Long replyId, ForumReplyService forumReplyService) {
        boolean deleted = forumReplyService.removeById(replyId);
        Map<String, Object> result = new HashMap<>();
        result.put("success", deleted);
        result.put("error", deleted ? null : "删除失败!");
        return result;
    }

    @Override
    // 验证是否为超级管理员
    public boolean verifyAdmin(HttpSession session) {
        User user = (User) session.getAttribute(LOGIN_USER);
        return user != null && user.getRole().equalsIgnoreCase("superAdmin");
    }
}